package com.hwl.utils;

import com.hwl.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {

    //爬取数据
    public List<Content> parseJD(String keywords) throws IOException{
        String url = "https://search.jd.com/Search?keyword=" + keywords + "&enc=utf-8";
        //解析网页，Jsoup返回的document对象就是浏览器对象
        Document document = Jsoup.parse(new URL(new String(url.getBytes(),"utf-8")), 30000);
        //在JS中可以使用的方法,这里都能用
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element.html());
        Elements elements = element.getElementsByTag("li");

        List<Content> goodsList = new ArrayList<>();
        for (Element e : elements) {
            String img = e.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = e.getElementsByClass("p-price").eq(0).text();
            String title = e.getElementsByClass("p-name").eq(0).text();

            goodsList.add(new Content(title,img,price));
        }
        return goodsList;
    }
}
